﻿using System;
using Microsoft.TeamFoundation.Client;

namespace TfsGiggle.Core
{
    /// <summary>
    /// An implementation of TfsConfigurationServer suited for unit test
    /// </summary>
    public class TfsConfigurationServerImpl : ITfsConfigurationServer, IDisposable
    {
        private Uri _uri;
        private TfsConfigurationServer _tfsConfigurationServer;

        /// <summary>
        /// TfsConfigurationServer implementation ctor
        /// </summary>
        /// <param name="uri"></param>
        public TfsConfigurationServerImpl(Uri uri)
        {
            _uri = uri;
            _tfsConfigurationServer = TfsConfigurationServerFactory.GetConfigurationServer(uri);
        }

        /// <summary>
        /// Name
        /// </summary>
        public string Name
        {
            get { return _tfsConfigurationServer.Name; }
        }

        /// <summary>
        /// Ensure authenticated
        /// </summary>
        public void EnsureAuthenticated()
        {
            _tfsConfigurationServer.EnsureAuthenticated();
        }

        /// <summary>
        /// Get the teamprojectcollection
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public ITfsTeamProjectCollection GetTeamProjectCollection(Guid guid)
        {
            return new TfsTeamProjectCollectionImpl(this._tfsConfigurationServer, guid);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_tfsConfigurationServer != null)
                {
                    _tfsConfigurationServer.Dispose();
                    _tfsConfigurationServer = null;
                }
            }
        }

        /// <summary>
        /// Go away
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Get a service
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        public object GetService(Type serviceType)
        {
            if (serviceType == typeof(IVersionControlServer))
            {
                return GetService(serviceType);
            }
            return null;
        }
    }
}
